package com.spy.material.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.util.List;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.spy.common.exception.base.BaseException;
import com.spy.common.utils.DateUtils;
import com.spy.material.domain.Inventory;
import com.spy.material.domain.InventoryDetail;
import com.spy.material.domain.PurchaseOrderDetail;
import com.spy.material.dto.PurchaseOrderCreateDTO;
import com.spy.material.dto.PurchaseOrderDetailCreateDTO;
import com.spy.material.dto.PurchaseOrderQueryDTO;
import com.spy.material.mapper.InventoryDetailMapper;
import com.spy.material.mapper.InventoryMapper;
import com.spy.material.mapper.PurchaseOrderDetailMapper;
import com.spy.material.vo.PurchaseOrderPageVO;
import com.spy.material.vo.PurchaseOrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spy.material.mapper.PurchaseOrderMapper;
import com.spy.material.domain.PurchaseOrder;
import com.spy.material.service.IPurchaseOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Arrays;
/**
 * 采购管理Service业务层处理
 * 
 * @author twc
 * @date 2025-11-09
 */
@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderMapper, PurchaseOrder> implements IPurchaseOrderService
{
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private PurchaseOrderDetailMapper purchaseOrderDetailMapper;
    @Autowired
    private InventoryMapper inventoryMapper;
    @Autowired
    private InventoryDetailMapper inventoryDetailMapper;

    /**
     * 查询采购管理
     * 
     * @param id 采购管理主键
     * @return 采购管理
     */
    @Override
    public PurchaseOrder selectPurchaseOrderById(Long id)
    {
                return getById(id);
    }

    /**
     * 查询采购管理列表
     * 
     * @param purchaseOrder 采购管理
     * @return 采购管理
     */
    @Override
    public List<PurchaseOrder> selectPurchaseOrderList(PurchaseOrder purchaseOrder)
    {
        return purchaseOrderMapper.selectPurchaseOrderList(purchaseOrder);
    }

    /**
     * 新增采购管理
     * 
     * @param purchaseOrder 采购管理
     * @return 结果
     */
    @Override
    public int insertPurchaseOrder(PurchaseOrder purchaseOrder)
    {
        purchaseOrder.setCreateTime(DateUtils.getNowDate());
                return save(purchaseOrder) ? 1 : 0;
    }

    /**
     * 修改采购管理
     * 
     * @param purchaseOrder 采购管理
     * @return 结果
     */
    @Override
    public int updatePurchaseOrder(PurchaseOrder purchaseOrder)
    {
        purchaseOrder.setUpdateTime(DateUtils.getNowDate());
                return updateById(purchaseOrder) ? 1 : 0;
    }

    /**
     * 批量删除采购管理
     * 
     * @param ids 需要删除的采购管理主键
     * @return 结果
     */
    @Override
    public int deletePurchaseOrderByIds(Long[] ids)
    {
                return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除采购管理信息
     * 
     * @param id 采购管理主键
     * @return 结果
     */
    @Override
    public int deletePurchaseOrderById(Long id)
    {
                return removeById(id) ? 1 : 0;
    }

    @Override
    public PurchaseOrderPageVO all(PurchaseOrderQueryDTO purchaseOrderQueryDTO) {
        PageHelper.startPage(purchaseOrderQueryDTO.getPage(),purchaseOrderQueryDTO.getPageSize());
        Page<PurchaseOrderVO> page = purchaseOrderMapper.all(purchaseOrderQueryDTO);
        return new PurchaseOrderPageVO(page.getTotal(), page.getResult());
    }

//    @Override
//    @Transactional
//    public void add(PurchaseOrderCreateDTO purchaseOrderCreateDTO) {
//        PurchaseOrder purchaseOrder = new PurchaseOrder();
//        BeanUtils.copyProperties(purchaseOrderCreateDTO,purchaseOrder);
//        insertPurchaseOrder(purchaseOrder);
//
//        for (PurchaseOrderDetail purchaseOrderDetail : purchaseOrderCreateDTO.getDetails()) {
//            Long id = purchaseOrder.getId();
//            purchaseOrderDetail.setPurchaseOrderId(id);
//            purchaseOrderDetailMapper.insertPurchaseOrderDetail(purchaseOrderDetail);
//        }
//    }

    @Override
    @Transactional
    public void add(@RequestBody PurchaseOrderCreateDTO purchaseOrderCreateDTO) {
        // 1. 保存采购单主表
        PurchaseOrder purchaseOrder = new PurchaseOrder();
        BeanUtils.copyProperties(purchaseOrderCreateDTO, purchaseOrder);
        insertPurchaseOrder(purchaseOrder);

        // 2. 保存采购明细并更新库存
        for (PurchaseOrderDetailCreateDTO detailDTO : purchaseOrderCreateDTO.getDetails()) {
            // 将DTO转换为实体
            PurchaseOrderDetail purchaseOrderDetail = new PurchaseOrderDetail();
            BeanUtils.copyProperties(detailDTO, purchaseOrderDetail);
            purchaseOrderDetail.setPurchaseOrderId(purchaseOrder.getId());
            purchaseOrderDetailMapper.insertPurchaseOrderDetail(purchaseOrderDetail);

            // 3. 更新库存总表
            updateInventoryForPurchase(purchaseOrderCreateDTO, detailDTO, purchaseOrder);

            // 4. 记录库存明细
            addInventoryDetailForPurchase(purchaseOrderCreateDTO, detailDTO, purchaseOrder, purchaseOrderDetail);
        }
    }

    /**
     * 采购入库 - 更新库存总表
     */
    private void updateInventoryForPurchase(PurchaseOrderCreateDTO purchaseOrderCreateDTO,
                                            PurchaseOrderDetailCreateDTO detailDTO,
                                            PurchaseOrder purchaseOrder) {
        // 查询当前库存记录
        Inventory inventory = inventoryMapper.selectByMaterialAndFullName(
                detailDTO.getMaterialName(),
                purchaseOrderCreateDTO.getFullName()
        );

        if (inventory == null) {
            // 如果库存不存在，创建新的库存记录
            inventory = new Inventory();
            inventory.setMaterialName(detailDTO.getMaterialName());
            inventory.setMaterialCategory(detailDTO.getMaterialCategory());
            inventory.setUnit(detailDTO.getUnit());
            inventory.setUnitPrice(detailDTO.getUnitPrice());
            inventory.setFullName(purchaseOrderCreateDTO.getFullName());
            inventory.setCurrentStock(detailDTO.getActualReceivedQuantity());
            inventory.setTotalAmount(detailDTO.getActualReceivedTotalPrice());

            inventoryMapper.insertInventory(inventory);
        } else {
            // 如果库存存在，更新库存数量和金额
            int newStock = inventory.getCurrentStock() + detailDTO.getActualReceivedQuantity();
            BigDecimal newTotalAmount = inventory.getTotalAmount().add(detailDTO.getActualReceivedTotalPrice());

            inventory.setCurrentStock(newStock);
            inventory.setTotalAmount(newTotalAmount);

            inventoryMapper.updateInventory(inventory);
        }
    }

    /**
     * 采购入库 - 记录库存明细
     */
    private void addInventoryDetailForPurchase(PurchaseOrderCreateDTO purchaseOrderCreateDTO,
                                               PurchaseOrderDetailCreateDTO detailDTO,
                                               PurchaseOrder purchaseOrder,
                                               PurchaseOrderDetail purchaseOrderDetail) {
        InventoryDetail inventoryDetail = new InventoryDetail();

        // 设置基本信息
        inventoryDetail.setMaterialName(detailDTO.getMaterialName());
        inventoryDetail.setMaterialCategory(detailDTO.getMaterialCategory());
        inventoryDetail.setUnit(detailDTO.getUnit());
        inventoryDetail.setFullName(purchaseOrderCreateDTO.getFullName());
        inventoryDetail.setTransactionType("入库");
        inventoryDetail.setDocumentNumber(purchaseOrder.getPurchaseOrderNumber());
        inventoryDetail.setQuantity(detailDTO.getActualReceivedQuantity());

        // 将字符串日期转换为 LocalDateTime
        try {
            LocalDate acceptanceDate = LocalDate.parse(purchaseOrderCreateDTO.getAcceptanceDate());
            LocalDateTime transactionDateTime = acceptanceDate.atTime(LocalTime.now());
            inventoryDetail.setTransactionDate(transactionDateTime);
        } catch (DateTimeParseException e) {
            throw new BaseException("验收日期格式错误，应为 YYYY-MM-DD 格式");
        }

        // 查询更新后的当前库存
        Inventory currentInventory = inventoryMapper.selectByMaterialAndFullName(
                detailDTO.getMaterialName(),
                purchaseOrderCreateDTO.getFullName()
        );
        inventoryDetail.setCurrentStock(currentInventory.getCurrentStock());

        // 设置关联ID
        inventoryDetail.setInventoryId(currentInventory.getId());
        inventoryDetail.setPurchaseOrderId(purchaseOrder.getId());

        inventoryDetailMapper.insertInventoryDetail(inventoryDetail);
    }
}
